package com.vogue.flowmeter.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.vogue.flowmeter.R;
import com.vogue.flowmeter.api.entity.ApiRecordEntity;
import com.vogue.flowmeter.api.entity.BaseResponse;
import com.vogue.flowmeter.api.event.DashboardMessageEvent;
import com.vogue.flowmeter.api.event.RecordMessageEvent;
import com.vogue.flowmeter.api.retrofit.NetWorkManager;
import com.vogue.flowmeter.profile.BleProfileService;
import com.vogue.flowmeter.util.PrefsUtils;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.NavDestination;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.Date;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DefaultObserver;
import io.reactivex.schedulers.Schedulers;

/**
 * 主页
 */
public class MainActivity extends AppCompatActivity {

    public BleProfileService.LocalBinder localBinder;
    protected static int OVERLAY_PERMISSION_REQ_CODE=110;
    private long mPressedTime;

    private ServiceConnection serviceConnection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            localBinder=(BleProfileService.LocalBinder)service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        Intent intent=new Intent(MainActivity.this,BleProfileService.class);
        bindService(intent,serviceConnection,BIND_AUTO_CREATE);

        setContentView(R.layout.activity_main);
        BottomNavigationView navView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
            @Override
            public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {

            }
        });
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);

        NavigationUI.setupWithNavController(navView, navController);
    }

    /**
     * navigation 里面的ID
     * @param resId
     */
    @SuppressLint("ResourceType")
    public void changeNavigation(@IdRes int resId){
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        navController.navigate(resId);
    }

    /**
     * 去操作台
     * @param messageEvent
     */
    @Subscribe
    public void toDashboard(DashboardMessageEvent messageEvent){
        if ("Dashboard".equals(messageEvent.getControl())){
            changeNavigation(R.id.navigation_dashboard);
        }else if ("Home".equals(messageEvent.getControl())){
            changeNavigation(R.id.navigation_home);
        }
        //发送事件出去
        RecordMessageEvent recordMessageEvent = new RecordMessageEvent(messageEvent.getControl(),messageEvent.getMessage());
        EventBus.getDefault().post(recordMessageEvent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        unbindService(serviceConnection);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == OVERLAY_PERMISSION_REQ_CODE) {
            if (Build.VERSION.SDK_INT >= 23) {
                if (!Settings.canDrawOverlays(this)) {
                    Toast.makeText(this, "权限授予失败，无法开启悬浮窗", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(this, "悬浮弹窗权限授予成功！", Toast.LENGTH_LONG).show();
                }
            }
        }
    }
    /**
     * 连接
     * @param device
     */
    public void onConnection(BluetoothDevice device){

        if ( Build.VERSION.SDK_INT>= 23 ) {
            if (Settings.canDrawOverlays(this)) {
                localBinder.onConnection(device);
            }else {
                //Toast.makeText(this, "没有悬浮窗权限m,去开启悬浮窗权限", Toast.LENGTH_LONG).show();
                new AlertDialog.Builder(this)
                        .setTitle("授权提醒")
                        .setMessage("没有悬浮窗权限,去开启悬浮窗权限")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent  intent=new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                                intent.setData(Uri.parse("package:" + getPackageName()));
                                intent.putExtra("device",device);
                                startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
                            }
                        })
                        .show();
            }
        }else {
            localBinder.onConnection(device);
        }


    }

    /**
     * 订阅消息  保存操作记录
     * @param messageEvent
     */
    @Subscribe
    public void saveRecord(RecordMessageEvent messageEvent){
        RxPermissions rxPermissions=new RxPermissions(this);
        rxPermissions.request(Manifest.permission.INTERNET,Manifest.permission.READ_PHONE_STATE).subscribe(aBoolean -> {
            if (aBoolean){
                ApiRecordEntity apiRecord=new ApiRecordEntity();
                apiRecord.setCreateTime(new Date().getTime());
                apiRecord.setData(messageEvent.getMessage());
                apiRecord.setOperationName(messageEvent.getControl());
                String deviceId= PrefsUtils.getInstance(MainActivity.this).get("deviceId","");
                if(TextUtils.isEmpty(deviceId)){
                    return;
                }
                apiRecord.setDeviceId(deviceId);
                NetWorkManager
                        .getInstance()
                        .getBleApiService()
                        .saveRecord(apiRecord)
                        .subscribeOn(Schedulers.io())
                        .doOnSubscribe(disposable -> {

                        })
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new DefaultObserver<BaseResponse>() {
                            @Override
                            public void onNext(BaseResponse response) {
                                Log.e(MainActivity.class.getName(),response.getMsg());
                            }

                            @Override
                            public void onError(Throwable e) {
                                Log.e(MainActivity.class.getName(),e.getMessage());

                            }

                            @Override
                            public void onComplete() {

                            }
                        });
            }
        });
    }
    @Override
    public void onBackPressed() {
        //获取第一次按键时间
        long mNowTime = System.currentTimeMillis();
        //比较两次按键时间差
        if ((mNowTime - mPressedTime) > 2000) {
            Toast.makeText(this,"再按一次退出",Toast.LENGTH_LONG).show();
            mPressedTime = mNowTime;
        } else {
            //super.onBackPressed();
            exitApp(getApplicationContext());
        }
    }
    public static void exitApp(Context context){
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.AppTask> appTaskList = activityManager.getAppTasks();
        for (ActivityManager.AppTask appTask : appTaskList) {
            appTask.finishAndRemoveTask();
        }
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }
}